from util import app
from werkzeug.utils import ImportStringError, find_modules, import_string

# 初始化项目
def create_app(config=None):

    # 判断是否 开启 session
    if config['session']:
        from muffin_session import Plugin as Session
        session = Session()
        session.setup(app, secret_key=config['session_key'], auto_manage=True)

    # 注册路由
    try:
        # 遍历得到配置里面的模块
        for key, value in config['module'].items():
            add_route('app.controller.'+key, app, value)
    except ImportStringError:
        ...
    return app

# 注册蓝图
def add_route(root, app, prefix='/'):

    # 遍历模块列表
    for name in find_modules(root, recursive=True):
        mod = import_string(name)
        # 判断是否有 app
        if hasattr(mod, 'app'):
            # 注册路由
            app.route(prefix)(mod.app)